<template>
  <div id="div1">
    <div id="div1-1">
      <vxe-button class="div1-1-button1" @click="addMenu">新增菜单</vxe-button>
      <vxe-button class="div1-1-button2" @click="saveMenu">保存</vxe-button>
    </div>
    <div id="div1-2">
      <vxe-table :tree-config="treeConfig" keep-source ref="t1Ref" height="100%"
                 :edit-config="{ trigger: 'click', mode: 'cell',activeMethod:()=>true }" @checkbox-change="changeMenu"
                 :checkbox-config="{ highlight: true }" auto-resize :data="tableData" @cell-click="handleCellClick">
        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
        <vxe-table-column type="seq" width="100" tree-node></vxe-table-column>
        <vxe-table-column field="module" title="模块" :edit-render="{
                               immediate: true,
                                name: '$select',
                                props: {type: 'select'},
                                options: moduleOptions,
                                events: {
                                }
        }"></vxe-table-column>
        <vxe-table-column field="menuName" title="菜单名称" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}
        }"></vxe-table-column>
        <vxe-table-column field="status" title="状态" :edit-render="{
                               immediate: true,
                                name: '$select',
                                props: {type: 'select'},
                                options: statusOptions,
                                events: {
                                }
        }"></vxe-table-column>
        <vxe-table-column field="viewName" title="资源"></vxe-table-column>
        <vxe-table-column align="center" header-align="center" :width="300" title="操作">
          <template slot-scope="scope">
            <div style="text-align: center;width: 100%;">
              <el-button size="mini" @click="insertSubMenu(scope)">新增</el-button>
              <el-button size="mini" @click="delSubMenu(scope)">删除</el-button>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
    <el-dialog title="新增子菜单" :visible.sync="subMenuShow" center>
      <div>
        <div class="rowDiv">
          <el-label class="label1">所属模块：</el-label>
          <el-select class="input1" v-model="subMenu.module" placeholder="请选择">
            <el-option
                v-for="item in moduleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          <el-label class="label2">子菜单名称：</el-label>
          <el-input class="input2" v-model="subMenu.menuName"></el-input>
        </div>
        <div class="rowDiv">
          <el-label class="label1">状态：</el-label>
          <el-select class="input1" v-model="subMenu.status" placeholder="请选择">
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div style="width: 100%; height:90px; border: solid 1px; position: relative; overflow: hidden">
          <el-label class="label1">描述：</el-label>
          <el-input style="display: inline-block; width: 70%; height: 90px; position: absolute;left: calc(5% + 110px)"
                    :rows="2"
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="subMenu.description">
          </el-input>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubMenu">取 消</el-button>
        <el-button type="primary" @click="saveSubMenu">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择资源" :visible.sync="selectViewShow" center>
      <el-table ref="t3Ref" :data="viewData" class="basic-table" max-height="300" @selection-change="changeView">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column property="module" label="模块" width="150"></el-table-column>
        <el-table-column property="viewName" label="资源名" width="150"></el-table-column>
        <el-table-column property="type" label="类型" width="150"></el-table-column>
        <el-table-column property="routerPath" label="路由地址"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectViewShow = false">取 消</el-button>
        <el-button type="primary" @click="confireView">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: "MenuList",
  data() {
    return {
      statusOptions: [
        {label: '正常', value: '1'},
        {label: '禁用', value: '0'},
      ],
      moduleOptions: [
        {label: '个人中心', value: '个人中心'},
        {label: '控制台', value: '控制台'},
        {label: '首页', value: '首页'},
      ],
      tableData: [
        {
          module: '个人中心', menuName: '菜单管理', status: '1', viewName: 'menu', children: [
            {
              module: '个人中心1', menuName: '菜单管理', status: '1', viewName: 'menu', children: [
                {module: '个人中心1-1', menuName: '菜单管理', status: '1', viewName: 'menu', children: []},
                {module: '个人中心1-4', menuName: '菜单管理', status: '1', viewName: 'menu', children: []}
              ]
            },
            {module: '个人中心2', menuName: '菜单管理', status: '1', viewName: 'menu', children: []},
            {module: '个人中心3', menuName: '菜单管理', status: '1', viewName: 'menu', children: []},
          ]
        },
        {module: '个人中心11', menuName: '菜单管理', status: '1', viewName: 'menu', children: []},
      ],
      selectedData: [],
      treeConfig: {
        // 指定子节点字段名
        children: 'children',
        // 默认是否全部展开
        expandAll: true,
      },
      selectedMenu: {},
      subMenuShow: false,
      subMenu: {},
      // 选择资源的对话框是否显示
      selectViewShow: false,
      // 接口表
      viewData: [],
      // 选中的接口
      changedViews:[],
    }
  },
  mounted() {
    this.loadData();
  },
  computed: {},
  methods: {
    addMenu() {
      const self = this;
      self.$refs.t1Ref.insertAt({}, -1);
    },
    changeMenu({records}) {
      this.selectedData = records;
      console.log('rows', JSON.stringify(records))
    },
    changeAllMenu(records) {
      console.log('all', JSON.stringify(records));
    },
    loadData() {
      request({
        url: '/user/menu/tree',
        method: 'get',
      }).then(response => {
        if (response && response.data) {
          console.log('response', response);
          this.tableData = response.data;
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('加载数据失败')
      })
    },
    saveMenu() {
      const self = this;
      const {
        insertRecords,
        updateRecords,
        removeRecords
      } = JSON.parse(JSON.stringify(self.$refs.t1Ref.getRecordset()));
      request({
        url: '/user/menu/batch',
        method: 'post',
        data: {
          insertAndUpdate: updateRecords.concat(insertRecords),
          del: removeRecords
        }
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          this.loadData();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    },
    // 全局单元格点击事件
    handleCellClick({row, column, rowIndex}) {
      const self = this;
      if (column.property==='viewName'){
        self.selectedMenu = row;
        self.loadViewData(()=>{
          self.selectViewShow = true;
        })
      }

      // row: 当前行数据
      // column: 当前列配置
      // $event: 原生事件对象
      console.log('row', row);
      console.log('rowIndex', rowIndex);
      console.log('column', column);
    },
    insertSubMenu(scope) {
      const self = this;
      // 保存操作的用户信息
      self.selectedMenu = scope.row;
      self.subMenu.pid = scope.row.id;
      self.subMenuShow = true;
    },
    delSubMenu(scope){
      const self = this;
      request({
        url: '/user/menu/batch',
        method: 'post',
        data: {
          del: [scope.row]
        }
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          self.subMenu.pid = '';
          self.subMenuShow = false;
          this.loadData();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    },
    saveSubMenu(){
      const self = this;
      request({
        url: '/user/menu/batch',
        method: 'post',
        data: {
          insertAndUpdate: [self.subMenu]
        }
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          self.subMenu.pid = '';
          self.subMenuShow = false;
          this.loadData();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    },
    cancelSubMenu(){
      const self = this;
      self.subMenuShow = false;
      self.subMenu.pid = '';
    },
    changeView(val){
      const self = this;
      // 如果选中数据大于1，提示框
      if (self.changedViews.length>1){
        self.$message.error('只能选择一个资源');
      }
      self.changedViews = val;
    },
    confireView(){
      const self = this;
      const menuId = self.selectedMenu.id;
      request({
        url: '/user/menu',
        method: 'put',
        data: {
          id: menuId,
          viewId: self.changedViews[0].id,
          viewName: self.changedViews[0].viewName
        }
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          self.selectViewShow = false;
          this.loadData();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    },
    loadViewData(callBack){
      request({
        url: '/user/view',
        method: 'get',
      }).then(response => {
        if (response && response.data) {
          const tempList = [];
          response.data.records.forEach(item => {
            tempList.push({
              id: item.id,
              module: item.module,
              viewName: item.viewName,
              type: item.type,
              routerPath: item.routerPath,
            })
          })
          this.viewData = tempList;
        }
        if (callBack && typeof callBack === 'function') {
          callBack();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('加载数据失败')
      })
    },
  }
}
</script>

<style scoped>
#div1 {
  width: 100%;
  height: 100%;
  position: relative;
}

#div1-1 {
  width: 100%;
  height: 10%;
  margin-bottom: 10px;
  position: relative;
  overflow: hidden;
}

.div1-1-button1 {
  top: 20px;
  right: 20px;
  width: 80px;
  position: absolute;
}

.div1-1-button2 {
  top: 20px;
  right: 120px;
  position: absolute;
  width: 80px;
}

.div1-1-button3 {
  top: 20px;
  right: 230px;
  position: absolute;
  width: 80px;
}

#div1-2 {
  width: 100%;
  height: Calc(90% - 10px);
  background-color: #606376;
  border-radius: 10px;
  padding: 10px;
  position: absolute;
}

#div1-2 .vxe-table {
}

::v-deep .vxe-table--header-wrapper {
  background-color: #606376 !important;
}

::v-deep .vxe-table--header-wrapper .vxe-header--row {
  background-color: #606376 !important;
  color: white;
}

::v-deep .vxe-table--body-wrapper {
  background-color: #606376 !important;
}

::v-deep .vxe-table--body-wrapper .vxe-body--row {
  background-color: #606376 !important;
  color: white;
}

::v-deep .vxe-tree-icon {
  display: inline-block !important;
  visibility: visible !important;
}

.rowDiv {
  width: 100%;
  height: 40px;
  border: solid 1px;
  position: relative;
  overflow: hidden
}

.label1 {
  position: absolute;
  font-size: medium;
  align-content: center;
  height: 40px;
  width: 100px;
  left: calc(5%);
}

.input1 {
  display: inline-block;
  width: 150px;
  height: 40px;
  position: absolute;
  left: calc(5% + 110px)
}

.label2 {
  position: absolute;
  height: 40px;
  left: calc(60%);
  width: 100px;
  font-size: medium;
  align-content: center;
}

.input2 {
  display: inline-block;
  height: 40px;
  width: 150px;
  position: absolute;
  left: calc(60% + 110px);
}

</style>